<!-- 分页器 -->
<template>
  <div class="xtx-pagination">
    <a v-if="CurrentPage > 1" href="javascript:;" @click="changePage(CurrentPage - 1)">上一页</a>
    <a v-else href="javascript:;" class="disabled">上一页</a>
    <span v-show="CurrentPage > pager.offset + 1">...</span>
    <a
      href="javascript:;"
      v-for="i in pager.btnArr"
      :class="{ active: CurrentPage === i }"
      :key="i"
      @click="changePage(i)"
    >{{ i }}</a>
    <span v-show="CurrentPage < pager.end">...</span>
    <a v-if="CurrentPage < pager.end" @click="changePage(CurrentPage + 1)" href="javascript:;">下一页</a>
    <a v-else href="javascript:;" class="disabled">下一页</a>
  </div>
</template>

<script>
import { computed, ref, watch } from "vue"

export default {
  name: 'Pagination',
  props: {
    Total: {
      type: Number,
      default: 100
    },
    pageSize: {
      type: Number,
      default: 10
    },
    CurrentPage: {
      type: Number,
      default: 1
    }
  },
  setup(props, { emit }) {
    // 总条数
    const Total = ref(95)
    // 每页条数
    const pageSize = ref(10)
    // 当前第几页
    const CurrentPage = ref(9)
    // 按钮个数
    const BtnCount = 5

    // 重点：根据上述数据得到（总页数，起始页码，结束页码，按钮数组）
    const pager = computed(() => {
      // 页面总条数
      let pageCount = Math.ceil(Total.value / pageSize.value)
      let offset = Math.floor(BtnCount / 2)
      let start = CurrentPage.value - offset
      let end = start + BtnCount - 1

      if (start < 1) {
        start = 1
        end = (start + BtnCount - 1) > pageCount ? pageCount : (start + BtnCount - 1)
      }
      if (end > pageCount) {
        end = pageCount
        start = (end - BtnCount + 1) < 1 ? 1 : (end - BtnCount + 1)
      }

      const btnArr = []
      for (let i = start; i <= end; i++)
        btnArr.push(i)

      return { pageCount, start, end, btnArr, offset }
    })


    watch(props, () => {
      Total.value = props.Total;
      pageSize.value = props.pageSize
      CurrentPage.value = props.CurrentPage
    }, { immediate: true })


    const changePage = newPage => {
      if (CurrentPage.value !== newPage) {
        CurrentPage.value = newPage
        // 通知父组件最新页码
        emit('current-change', newPage)
      }
    }
    return {
      pager, CurrentPage, changePage
    }
  }
}
</script>

<style scoped lang="less">
.xtx-pagination {
  display: flex;
  justify-content: center;
  padding: 30px;
  > a {
    display: inline-block;
    padding: 5px 10px;
    border: 1px solid #e4e4e4;
    border-radius: 4px;
    margin-right: 10px;
    &:hover {
      color: @xtxColor;
    }
    &.active {
      background: @xtxColor;
      color: #fff;
      border-color: @xtxColor;
    }
    &.disabled {
      cursor: not-allowed;
      opacity: 0.4;
      &:hover {
        color: #333;
      }
    }
  }
  > span {
    margin-right: 10px;
  }
}
</style>